package com.leyantech.ecp.agenx.common.converter.output;

import static com.leyantech.ecp.agenx.common.config.ConfigManager.IMAGE_DOMAIN;

import com.leyantech.ai.DialogueQuestion;
import com.leyantech.ai.DialogueReply;
import com.leyantech.ai.DialogueReplyContext;
import com.leyantech.ai.DialogueReplyContext.DialogueReplyType;
import com.leyantech.ai.JobQueueName;
import com.leyantech.ecp.agenx.common.entity.reply.ReplyContext;
import com.leyantech.ecp.agenx.common.entity.reply.ReplyCtx;
import com.leyantech.ecp.agenx.common.message.EnumWsFnType;
import com.leyantech.ecp.agenx.common.message.MessageHelper;
import com.leyantech.ecp.agenx.common.service.StoreConfigService;
import com.leyantech.ecp.agenx.common.utils.PbPrintHelper;

import com.google.inject.Inject;
import com.google.inject.Singleton;
import io.vertx.core.json.JsonArray;
import io.vertx.core.json.JsonObject;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;


/**
 * @author eahau, {@literal <eahau@foxmail.com>}
 * @date 2022-11-01.
 */
@Slf4j
@Singleton
public class PinDuoDuoReplyConverter implements DialogueReplyConverter {

  private final StoreConfigService storeConfigService;

  @Inject
  public PinDuoDuoReplyConverter(StoreConfigService storeConfigService) {
    this.storeConfigService = storeConfigService;
  }

  @Override
  public JsonObject apply(DialogueReply dialogueReply) {
    String replyJson = PbPrintHelper.toJson(dialogueReply.getDialogueReplyV2());

    JsonObject reply = new JsonObject(replyJson);

    ReplyContext replyContext = ReplyContext.create(dialogueReply);

    final String storeId = dialogueReply.getStoreId();
    final String assistantId = dialogueReply.getAssistantId();
    final String deviceNo = replyContext.getDeviceNo();

    // 如果本身就是转人工, 需要将内容置为 noResponse
    replyContext.takeNotReplyResponse();
    if (replyContext.isCanNotReply()) {
      // pdd 对于不能回复的，不再直接 转 updateContentToSwitchToHuman
      replyContext.updateReplyToNoopWithOther();
    }

    // 检查是否包含订单id，来决定是否追加订单id
    String orderId = replyContext.getOrderId();
    if (StringUtils.isNotEmpty(orderId)) {
      log.debug("ws 回复将带有 orderId:{}, origin:{}", orderId, replyJson);
      reply.put("orderId", orderId);
    }

    // lxk 不做判断，因为 lxk 不属于我们的产品
    if (dialogueReply.getDialogueReplyV2().getJobQueueName() != JobQueueName.LXK
        && storeConfigService.isAssistantForbidden(storeId, assistantId, deviceNo)) {
      log.warn("storeId: {}, assistantId: {}，坐席被限制，强制转人工", storeId, assistantId);
      replyContext.setNotReplyReason("坐席被限制，强制转人工");
      replyContext.updateContentToSwitchToHuman();
    }

    replyJson = checkImage(reply.toString());

    reply = new JsonObject(replyJson);

    addReplyCtx(replyContext, reply);

    return MessageHelper.buildMessage(EnumWsFnType.DIALOGUE_ANSWER_REPLY, reply);
  }

  private static final String IMAGE_PREFIX = "pdd/s/";

  private String checkImage(String originArgs) {

    String[] split = originArgs.split(IMAGE_PREFIX);
    if (split.length < 2) {
      return originArgs;
    }

    // 以下方法将图片 imageId 转化为 图片url + hash
    for (int i = 1; i < split.length; i++) {
      String[] brr = split[i].split("\"");

      String tokenId = brr[0];
      String imageId = IMAGE_PREFIX + tokenId;

      String hashId = tokenId.split("/i/")[1].split("\\.")[0];

      String imageUrl = IMAGE_DOMAIN.get() + imageId + "?hash=" + hashId;

      originArgs = originArgs.replaceAll(imageId, imageUrl);

    }

    return originArgs;
  }

  /**
   * reply ctx.用于给客户端一个回复ctx.
   */
  protected void addReplyCtx(ReplyContext replyContext, JsonObject reply) {
    DialogueReplyContext dialogueReplyContext = replyContext.getDialogueReplyContext();
    if (dialogueReplyContext.getReplyType() == DialogueReplyType.DRT_INVALID) {
      if (replyContext.isCanNotReply()) {
        return;
      }
      // 一f般属于营销消息.
      ReplyCtx replyCtx = new ReplyCtx();
      replyCtx.setCanReply(true);
      replyCtx.setOtherReplyInfoList(replyContext.getNotReplyJsonList());
      reply.put("replyCtx", replyCtx.toJsonObject());

      return;
    }
    ReplyCtx replyCtx = new ReplyCtx();

    // 将一些灯效等信息添加进去.
    JsonArray notReplyJsonList = replyContext.getNotReplyJsonList();
    replyCtx.setOtherReplyInfoList(notReplyJsonList);

    if (StringUtils.isNotBlank(replyContext.getNotReplyReason())) {
      replyCtx.setCanReply(false);
      replyCtx.setReason(replyContext.getNotReplyReason());
    } else {
      if ("EXPECTED".equals(dialogueReplyContext.getReason()) || !replyContext.isCanNotReply()) {
        replyCtx.setCanReply(true);
      } else {
        replyCtx.setCanReply(false);
        replyCtx.setReason(dialogueReplyContext.getReason());
      }
    }
    DialogueQuestion question = dialogueReplyContext.getQuestion(0);
    replyCtx.setCustomerQuery(question.getQuery());

    replyCtx.setBuyerEmotion(dialogueReplyContext.getPolarity());

    reply.put("replyCtx", replyCtx.toJsonObject());
  }

}
